﻿using Core.Attributes;
using Core.Extensions;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Models;
using Gridify;
using Gridify.EntityFramework;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Audit.Features.Queries;

[NoLogging]
public class AuditTrailsWithPaginationQuery : GridifyQuery, IRequest<PaginatedData<AuditTrailDto>>
{
}

public class AuditTrailsWithPaginationQueryHandler :
         IRequestHandler<AuditTrailsWithPaginationQuery, PaginatedData<AuditTrailDto>>
{
    private readonly IIdentityDbContext _db;

    public AuditTrailsWithPaginationQueryHandler(
        IIdentityDbContext db)
    {
        _db = db;
    }

    public async Task<PaginatedData<AuditTrailDto>> Handle(AuditTrailsWithPaginationQuery request, CancellationToken cancellationToken)
    {
        var query =
            from audit in _db.AuditTrails.AsNoTracking()
            join user in _db.Users.AsNoTracking() on audit.UserId equals user.Id into userGroup
            from u in userGroup.DefaultIfEmpty()
            select new AuditTrailDto
            {
                Id = audit.Id,
                UserId = audit.UserId,
                Username = u != null ? u.Username : null,
                Operation = audit.Operation,
                Entity = audit.Entity,
                DateTime = audit.DateTime,
                PreviousValues = audit.PreviousValues,
                NewValues = audit.NewValues,
                ModifiedProperties = audit.ModifiedProperties,
                PrimaryKey = audit.PrimaryKey
            };

        var result = await query.GridifyAsync(request, cancellationToken);

        return result.ToPaginatedList(request.Page, request.PageSize);
    }
}
